import classNames from 'classnames';
import { connect } from 'react-redux';
// import {compose} from 'redux';

import PropTypes from 'prop-types';
import bindAll from 'lodash.bindall';
import bowser from 'bowser';
import React from 'react';

import VM from 'scratch-vm';
import Box from '../box/box.jsx';
import Button from '../button/button.jsx';

// import {MenuItem, MenuSection} from '../menu/menu.jsx';
// import MenuBarMenu from './menu-bar-menu.jsx';
// import DeletionRestorer from '../../containers/deletion-restorer.jsx';
// import TurboMode from '../../containers/turbo-mode.jsx';

import SBFileUploader from '../../containers/sb-file-uploader.jsx';
import SB3Downloader from '../../containers/sb3-downloader.jsx';
import Divider from '../divider/divider.jsx';
import ProjectTitleInput from './project-title-input.jsx';
import LoginDropdown from './login-dropdown.jsx';
import AccountNav from '../../containers/account-nav.jsx';

import { showStandardAlert, showInlineAlerts } from '../../reducers/alerts';
import {
	getIsShowingProject,
	copyProject,
	updateProject,
	setProjectTitle,
	setProjectShare,
	setLessonId,
} from '../../reducers/project-state';
import {
	fileMenuOpen,
	openFileMenu,
	closeFileMenu,
	editMenuOpen,
	openEditMenu,
	closeEditMenu,
	loginMenuOpen,
	openLoginMenu,
	closeLoginMenu,
	accountMenuOpen,
	openAccountMenu,
	closeAccountMenu,
} from '../../reducers/menus';

import styles from './menu-bar.css';
import helpIcon from '../../lib/assets/icon--tutorials.svg';
import remixIcon from './icon--remix.svg';
import shareIcon from './icon--share.svg';
// import saveIcon from './icon-save.svg';
// import sethomeworkIcon from './icon--sethomework.svg';
import { setSession, initializedSession } from '../../reducers/session';
import {
	activateCourseCards,
	viewCards,
	closeCards,
} from '../../reducers/cards'; // 课程卡播放器：一个弹出式的小窗口
import {
	openMyProjectLibrary,
	openYxProjectLibrary,
} from '../../reducers/modals'; // 打开我的作品、优秀作品库
import {
	requestLogin,
	requestLogout,
	requestSaveProjectTitle,
	requestShareProject,
	requestCousreCard,
} from '../../session-api.js';

import Login from '../login/login.jsx';

class MenuBar extends React.Component {
	constructor(props) {
		super(props);
		bindAll(this, [
			'handleKeyPress',
			'handleClickNew',
			'handleClickCopyProject',
			'getSaveToComputerHandler',
			'restoreOptionMessage',

			'handleRestoreOption',
			'handleClickShare',
			'handleChangedProjectTitle',
			'handleRenderLogin',
			'handleLogout',
			'handleShowCourseCard',
		]);
	}
	componentDidMount() {
		document.addEventListener('keydown', this.handleKeyPress);
	}
	componentWillUnmount() {
		document.removeEventListener('keydown', this.handleKeyPress);
	}
	handleKeyPress(event) {
		// 监听按键消息
		const modifier = bowser.mac ? event.metaKey : event.ctrlKey;
		if (modifier && event.key === 's') {
			// Ctrl+s：保存作品
			// 用户已登录、作品为变更状态、不是其他用户的作品，则可保存到服务器
			if (
				this.props.isLogin &&
				!this.props.othersProject &&
				this.props.projectChanged
			) {
				this.props.onClickSave();
				event.preventDefault();
			}
		}
	}
	//componentDidUpdate (prevProps) {}
	handleRenderLogin() {
		//登录操作
		return (
			<Login
				onLogIn={(formData, restoreStateInLoginComponent) => {
					requestLogin(formData).then(
						(body) => {
							if (body.status == 'OK') {
								this.props.onSetSession(body);
								this.props.onRequestCloseAccount(); //关闭登录后的账号菜单：登录后会弹出账号菜单
							} else {
								alert(body.status); //提示用户登录不成功的原因
								restoreStateInLoginComponent();
							}
						},
						(err) => {
							restoreStateInLoginComponent();
						}
					);
					// new Promise((resolve, reject) => {
					//     requestLogin(resolve, reject, formData);
					// }).then(
					//     body => {
					//         if (body.status=="OK"){
					//             this.props.onSetSession(body);
					//             this.props.onRequestCloseAccount()//关闭登录后的账号菜单：登录后会弹出账号菜单
					//         } else {
					//             alert(body.status);//提示用户登录不成功的原因
					//             restoreStateInLoginComponent()
					//         }
					//     },
					//     err => {
					//         restoreStateInLoginComponent()
					//     }
					// );
				}}
			/>
		);
	}
	handleLogout() {
		//退出账号登录状态
		new Promise((resolve, reject) => {
			requestLogout(resolve, reject, `id=${this.props.userid}`);
		}).then(
			(body) => {
				this.props.onSetSession(initializedSession);
				//this.props.onRequestCloseAccount()//关闭登录菜单
			},
			(err) => {}
		);
	}
	handleShowCourseCard() {
		//打开或关闭教程卡窗口
		// this.props.onShowCourseCard();
		// this.props.onShowStandardAlert('正在导入……')
		// this.props.onShowStandardAlert('作品未能保存。作品未能保存。作品未能保存。')
		// return;
		if (this.props.courseCardsVisible) {
			this.props.onCloseCourseCards();
			return;
		}

		//判断是否已经从服务器获取了课程卡片内容
		if (this.props.courseCardContent) {
			this.props.onShowCourseCard();
		} else {
			new Promise((resolve, reject) => {
				requestCousreCard(resolve, reject, this.props._lesson_id);
			}).then(
				(body) => {
					if (body.status == 'ok') {
						this.props.onActivateCourseCard(body.src);
					} else {
						this.props.onSetLessonId(0);
						this.props.onShowStandardAlert(body.status); //提示用户登录不成功的原因
					}
				},
				(err) => {}
			);
		}
	}

	//新建一个作品
	handleClickNew() {
		//1、当前作品需要保存（如：新作品、新上传、复制、改编、改动过），提示用户是否保存或下载；
		//2、如果没有登录，不能保存，用户可考虑先下载或登录；
		let newProject = true;
		if (this.props.projectChanged) {
			//调用标准的JS confirm
			newProject = confirm('是否丢弃当前作品中尚未保存的内容？');
		}
		// this.props.onRequestCloseFile();//收起【文件】菜单栏

		if (newProject) {
			//开始新建作品
			//改变hash，在hash-parser-hoc.jsx中有监听此事件，即可新建作品
			window.location.hash = 'B'; //随意写一个字符，使hash产生变化，才能触发监听事件
			//去除url中hash的空#字符
			history.pushState(
				'B',
				'B',
				window.location.pathname + window.location.search
			);
		}
	}
	//改编、复制作品
	handleClickCopyProject() {
		this.props.onClickCopyProject();
		this.props.onRequestCloseFile();
		//去除url中hash的空#字符
		history.pushState(
			'B',
			'B',
			window.location.pathname + window.location.search
		);
	}
	//保存作品到本机
	getSaveToComputerHandler(downloadProjectCallback) {
		return () => {
			this.props.onRequestCloseFile();
			downloadProjectCallback();
		};
	}
	//作品名称被修改时
	handleChangedProjectTitle(title) {
		// 空标题时，不做修改，直接使用以前的标题
		if (title === null || title === '' || title == this.props.projectTitle) {
			return;
		}

		if (
			!this.props.isLogin ||
			!this.props.userOwnsProject ||
			!this.props.isShowingProject
		) {
			//作品状态无需上传更新作品名，直接显示新作品名
			this.props.onSetProjectTitle(title);
			return;
		}

		//对于有正常ID的作品，标题改变时：保存新的作品名
		new Promise((resolve, reject) => {
			requestSaveProjectTitle(resolve, reject, this.props.projectId, title);
		}).then(
			(body) => {
				this.props.onSetProjectTitle(title);
				this.props.onShowInlineAlert('作品名已保存');
			},
			(err) => this.props.onShowStandardAlert('无法保存作品名。 请再试一次！')
		);
	}

	//分享作品
	//进入此函数前已判断：this.props.isLogin&&this.props.userOwnsProject&&this.props.isShowingProject
	handleClickShare(s) {
		requestShareProject(this.props.projectId, s).then(
			(body) => {
				if (body.status == 'ok') {
					this.props.onSetProjectShare(s);
				}
			},
			(err) => {}
		);
	}
	//【编辑】菜单中的撤销操作
	handleRestoreOption(restoreFun) {
		return () => {
			restoreFun();
			this.props.onRequestCloseEdit();
		};
	}

	restoreOptionMessage(deletedItem) {
		switch (deletedItem) {
			case 'Sprite':
				return '复原删除的角色';
			case 'Sound':
				return '复原删除的声音';
			case 'Costume':
				return '复原删除的造型';
			default: {
				return '恢复';
			}
		}
	}

	render() {
		return (
			<Box className={classNames(this.props.className, styles.menuBar)}>
				<div className={styles.mainMenu}>
					<div className={styles.fileGroup}>
						{/* LOGO 部分 */}
						<div className={classNames(styles.menuBarItem)}>
							<a href='/' target='_blank'>
								<img
									alt='来编程'
									className={classNames(styles.scratchLogo)}
									draggable={false}
									src={_scratch_logo}
								/>
							</a>
						</div>

						{/* 竖线组件 */}
						<Divider className={classNames(styles.divider)} />
						{!this.props.isLogin || this.props._lesson_id == 0 ? (
							[]
						) : (
							<>
								<div
									className={classNames(styles.menuBarItem, styles.hoverable)}
									onClick={this.handleShowCourseCard}
								>
									<img className={styles.helpIcon} src={helpIcon} />
									{this.props.courseCardsVisible ? '关闭教程' : '打开教程'}
								</div>
								<Divider className={classNames(styles.divider)} />
							</>
						)}

						<div
							className={classNames(styles.menuBarItem, styles.hoverable)}
							onClick={this.handleClickNew}
							// eslint-disable-next-line react/jsx-no-literals
						>
							新建一个作品
						</div>

						<SBFileUploader>
							{(className, renderFileInput, handleLoadProject) => (
								<div
									className={classNames(styles.menuBarItem, styles.hoverable)}
									onClick={handleLoadProject}
									// eslint-disable-next-line react/jsx-no-literals
								>
									从电脑中上传
									{renderFileInput()}
								</div>
							)}
						</SBFileUploader>

						{/* <SB3Downloader>{(className, downloadProjectCallback) => (
                            <div
                                className={classNames(styles.menuBarItem, styles.hoverable)}
                                onClick={this.getSaveToComputerHandler(downloadProjectCallback)}
                            // eslint-disable-next-line react/jsx-no-literals
                            >
                                保存到电脑
                            </div>
                        )}</SB3Downloader> */}
					</div>

					{/* 保存提示 */}
					{!this.props.isLogin ||
					!this.props.projectChanged ||
					this.props.othersProject ? (
						<div
							className={classNames(styles.menuBarItem, styles.disabled)}
							// eslint-disable-next-line react/jsx-no-literals
						>
							保存到云端
						</div>
					) : (
						<div className={styles.menuBarItem}>
							<Button
								className={classNames(
									styles.menuBarButton,
									styles.saveProjectButton
								)}
								// iconClassName={styles.remixButtonIcon}
								// iconSrc={saveIcon}
								onClick={this.props.onClickSave}
								// eslint-disable-next-line react/jsx-no-literals
							>
								保存到云端
							</Button>
						</div>
					)}

					{/* 作品标题：自己的作品时，可以修改，别人的作品时，只显示，不能修改 */}
					<div className={classNames(styles.menuBarItem, styles.growable)}>
						<React.Fragment>
							<ProjectTitleInput
								className={classNames(styles.titleFieldGrowable)}
								onSubmit={this.handleChangedProjectTitle}
							/>
						</React.Fragment>
					</div>

					<div className={classNames(styles.menuBarItem)}>
						{/* 改编组件 */}
						{this.props.isLogin && this.props.othersProject && (
							<Button
								className={classNames(styles.menuBarButton, styles.remixButton)}
								iconClassName={styles.remixButtonIcon}
								iconSrc={remixIcon}
								onClick={this.handleClickCopyProject}
								// eslint-disable-next-line react/jsx-no-literals
							>
								改编
							</Button>
						)}
					</div>
					{/* 分享组件 */}
					{this.props.isLogin &&
						this.props.userOwnsProject &&
						this.props.isShowingProject &&
						(!this.props.projectShared ? (
							<Button
								className={classNames(styles.menuBarButton, styles.shareButton)}
								iconClassName={styles.remixButtonIcon}
								iconSrc={shareIcon}
								onClick={() => this.handleClickShare(1)}
							>
								分享
							</Button>
						) : (
							<Button
								className={classNames(
									styles.menuBarButton,
									styles.shareButtonIsShared
								)}
								onClick={() => this.handleClickShare(0)}
							>
								取消分享
							</Button>
						))}
					{/* 保存提示 */}
					{this.props.inlineAlertContent && (
						<div className={styles.menuBarItem}>
							<div className={styles.inlineMessage}>
								{this.props.inlineAlertContent}
							</div>
						</div>
					)}
				</div>

				{/* 顶部菜单栏右侧部分*/}
				<div className={styles.accountInfoGroup}>
					<div
						className={classNames(styles.menuBarItem, styles.hoverable)}
						onClick={this.props.onOpenYxProjectLibrary}
						// eslint-disable-next-line react/jsx-no-literals
					>
						优秀作品
					</div>

					{this.props.isLogin ? (
						<div
							className={classNames(styles.menuBarItem, styles.hoverable)}
							onClick={this.props.onOpenMyProjectLibrary}
							// eslint-disable-next-line react/jsx-no-literals
						>
							我的作品
						</div>
					) : (
						<div
							className={classNames(styles.menuBarItem, styles.disabled)}
							// eslint-disable-next-line react/jsx-no-literals
						>
							我的作品
						</div>
					)}

					{/* 竖线组件 */}
					<Divider className={classNames(styles.divider)} />

					{this.props.isLogin ? (
						// ************ 用户已登录 ************
						<React.Fragment>
							<AccountNav
								className={classNames(styles.menuBarItem, styles.hoverable, {
									[styles.active]: this.props.accountMenuOpen,
								})}
								isOpen={this.props.accountMenuOpen}
								menuBarMenuClassName={classNames(styles.menuBarMenu)}
								onClick={this.props.onClickAccount}
								onClose={this.props.onRequestCloseAccount}
								onLogOut={this.handleLogout}
							/>
						</React.Fragment>
					) : (
						// ********* 用户未登录 ************
						<React.Fragment>
							<div
								className={classNames(styles.menuBarItem, styles.hoverable)}
								key='login'
								onMouseUp={this.props.onClickLogin}
							>
								登录|注册
								<LoginDropdown
									className={classNames(styles.menuBarMenu)}
									isOpen={this.props.loginMenuOpen}
									onClose={this.props.onRequestCloseLogin}
									renderLogin={this.handleRenderLogin}
								/>
							</div>
						</React.Fragment>
					)}
				</div>
			</Box>
		);
	}
}
MenuBar.propTypes = {
	//locale: PropTypes.string.isRequired,
	className: PropTypes.string,

	fileMenuOpen: PropTypes.bool,
	onClickFile: PropTypes.func,
	onRequestCloseFile: PropTypes.func,

	editMenuOpen: PropTypes.bool,
	onClickEdit: PropTypes.func,
	onRequestCloseEdit: PropTypes.func,

	onClickLogin: PropTypes.func,
	loginMenuOpen: PropTypes.bool,
	onRequestCloseLogin: PropTypes.func,

	accountMenuOpen: PropTypes.bool,
	onClickAccount: PropTypes.func,

	isShowingProject: PropTypes.bool,

	onClickSave: PropTypes.func,
	onClickCopyProject: PropTypes.func,

	onRequestCloseAccount: PropTypes.func,

	vm: PropTypes.instanceOf(VM).isRequired,
	inlineAlertContent: PropTypes.string,

	onOpenMyProjectLibrary: PropTypes.func,
	onOpenYxProjectLibrary: PropTypes.func,
};
//MenuBar.defaultProps = {};
const mapStateToProps = (state, ownProps) => {
	const _session = state.session;
	const _project = state.project;
	const loadingState = _project.loadingState;

	return {
		accountMenuOpen: accountMenuOpen(state),
		fileMenuOpen: fileMenuOpen(state),
		editMenuOpen: editMenuOpen(state),
		loginMenuOpen: loginMenuOpen(state),
		isShowingProject: getIsShowingProject(loadingState),

		vm: state.scratchGui.vm,
		inlineAlertContent: state.scratchGui.alerts.inlineContent, //提示内容

		//作品信息
		projectId: _project.projectId, //作品Id
		projectTitle: _project.title, //作品名称
		projectChanged: _project.projectChanged, //作品已被更改
		projectShared: _project.state == 0 ? false : true, //已经分享

		_lesson_id: _project.lesson_id, //课程卡对应的课时ID
		//card_count:_project.card_count,//课程卡数

		teacher_id: _project.teacher_id, //带有老师ID，说明作品是课堂作业，老师可以修改并保存

		//登录信息
		userid: _session.userid, //用户ID
		isLogin: _session.userid == 0 ? false : true, //是否已登录，登录后，可查看自己的作品展示
		// username: _session.userid==0 ? null: _session.nickname,//用户昵称
		userOwnsProject: _session.userid == _project.authorId, //用户自己的作品：可以修改、复制、分享等操作
		othersProject:
			_session.userid != _project.teacher_id &&
			_session.userid != _project.authorId &&
			_project.authorId != 0, //其他用户的作品：才可以改编

		//课时卡
		courseCardContent: state.cards.content, //课程卡ID
		courseCardsVisible: state.cards.visible, //课程卡是否已打开
	};
};

const mapDispatchToProps = (dispatch) => ({
	onClickFile: () => dispatch(openFileMenu()), //打开【文件】菜单
	onRequestCloseFile: () => dispatch(closeFileMenu()), //关闭【文件】菜单

	onClickEdit: () => dispatch(openEditMenu()), //打开【编辑】菜单
	onRequestCloseEdit: () => dispatch(closeEditMenu()), //关闭【编程】菜单

	onClickAccount: () => dispatch(openAccountMenu()), //打开右侧【用户账号】菜单
	onRequestCloseAccount: () => dispatch(closeAccountMenu()), //关闭【用户账号】菜单

	onClickCopyProject: () => dispatch(copyProject()), //改编、复制当前作品
	onClickSave: () => dispatch(updateProject()), //手动保存作品

	onClickLogin: () => dispatch(openLoginMenu()),
	onRequestCloseLogin: () => dispatch(closeLoginMenu()), //关闭登录菜单

	onSetSession: (session) => dispatch(setSession(session)), //设置session

	onShowStandardAlert: (msg, level) => dispatch(showStandardAlert(msg, level)), //显示标准提示
	onShowInlineAlert: (msg) => showInlineAlerts(dispatch, msg), //显示行内提示

	onSetProjectTitle: (title) => dispatch(setProjectTitle(title)),
	onSetProjectShare: (s) => dispatch(setProjectShare(s)),

	onSetLessonId: (c) => dispatch(setLessonId(c)), //激活课程卡
	onActivateCourseCard: (content) => dispatch(activateCourseCards(content)), //激活课程卡
	onShowCourseCard: () => dispatch(viewCards()), //显示课程卡
	onCloseCourseCards: () => dispatch(closeCards()), //关闭课程卡

	onOpenMyProjectLibrary: () => dispatch(openMyProjectLibrary()), // 打开我的作品库
	onOpenYxProjectLibrary: () => dispatch(openYxProjectLibrary()), // 打开作秀作品库
});

export default connect(mapStateToProps, mapDispatchToProps)(MenuBar);
// export default compose(
//     injectIntl,
//     connect(
//         mapStateToProps,
//         mapDispatchToProps
//     )
// )(MenuBar);
